package ddbs;

public class Work extends LocalWork {
    public static String STATUS = "swork";

    public String getStatus() {
        return Work.STATUS;
    }
    public Peer getPeer() {
        return ds.peer;
    }
    protected String formalSQL() {
        StringBuffer sql = new StringBuffer();
        ;
        sql.append("select");
        for (int i = 0; i < ds.fileds.length; ++i) {
            if (i == 0)
                sql.append(" ");
            else
                sql.append(",");
            sql.append(ds.fileds[i]);
        }
        if (ds.exfileds != null && ds.exfileds.length > 0) {
            for (int i = 0; i < ds.exfileds.length; i++) {
            	if (ds.fileds.length == 0){
            		sql.append(" " + ds.exfileds[i]);
            	}
            	else{
            		sql.append("," + ds.exfileds[i]);
            	}
            }
        }
        sql.append(" from " + ds.table);
        if (ds.limit != null && ds.limit.length > 0) {
            for (int i = 0; i < ds.limit.length; ++i) {
                if (i == 0)
                    sql.append(" where");
                if (i > 0)
                    sql.append(" and");
                sql.append(" " + ds.limit[i]);
            }
        }
        return sql.toString();
    }

    protected void handleLocal() {
        if (ds.peer.IsSelf()) {
            queryDatabase();
        } else {
            ds.peer.sendWork(this);
        }
    }

    public void handleResponse(MSG msg) {
        this.data = Data.deserialize(msg.len, msg.content);
        System.out.println("Work #"+this.id+" handleResponse and get data done size="+this.data.getSize());
        done();
    }

    /*
     * Format workload to msg
     */
    public MSG toMSG() {
        int peerid = this.ds.peer.getId();
        int peerlength = 1;
        int len = this.imsql.length() + 2;
        String content = new String();
        content = this.imsql + peerid;
        content = content + peerlength;
        return new MSG(Sched.msgType, Work.STATUS, this.id, len, content);
    }

}
